package com.tan.multitasking;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
/**
 * Constructs the frame with the component for showing the bouncing ball and start and close buttons.
 * 使用用于显示反弹球的组件以及开始和关闭按钮构建框架.
 * */
public class BounceFrame extends JFrame {
    private BallComponent component;
    public static final int STEPS = 1000;
    public static final int DELAY = 3;
/**
 * Constructs the frame with the component for showing the bouncing ball and Start and Close buttons
 * 使用用于显示反弹球的组件以及开始和关闭按钮构建框架
 * */
    public BounceFrame(){
        setTitle("Bounce");
        component = new BallComponent();
        add(component, BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel();
        //Start 按钮的处理程序将调用addBall方法。这个方法循环运行1000此move。每调用一次move，球就会移动一点。
        addButton(buttonPanel,"Start",event->addBall());
        addButton(buttonPanel,"Close",event->System.exit(0));
        add(buttonPanel,BorderLayout.SOUTH);
        pack();
    }

/**
 * Adds a button to a container.
 *  将按钮添加到容器。
 * */
    public void addButton(Container c, String title, ActionListener listener){
        JButton button = new JButton(title);
        c.add(button);
        button.addActionListener(listener);
    }

/**
 * Adds a bouncing ball to the panel and makes it bounce 1000 times.
 *  将反弹的球添加到面板中，使其反弹1000次。
 * */
    public void  addBall(){
        try {
            Ball ball = new Ball();
            component.add(ball);
/**
 * 球的移动。
 * */
            for (int i = 1;i<=STEPS;i++){
                ball.move(component.getBounds());
                component.paint(component.getGraphics());
                //休眠的毫秒数
                Thread.sleep(DELAY);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
